package com.shqcjd.yunweiyanoperator.ui.activity.staff;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.HiScene.HiDeviceCenterKit.core.HiDeviceKitEngine;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.logger.Logger;
import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.update.PgyUpdateManager;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.app.AppConstant;
import com.shqcjd.yunweiyanoperator.app.MyApp;
import com.shqcjd.yunweiyanoperator.jpush.TagAliasUtils;
import com.shqcjd.yunweiyanoperator.model.eventbus.FinishActivityEvent;
import com.shqcjd.yunweiyanoperator.model.eventbus.ReloginEvent;
import com.shqcjd.yunweiyanoperator.model.eventbus.TokenOvertimeEvent;
import com.shqcjd.yunweiyanoperator.model.pojo.ExtraJson;
import com.shqcjd.yunweiyanoperator.model.pojo.GoRegister;
import com.shqcjd.yunweiyanoperator.ui.activity.AnswerActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.LoginActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.remote.DeviceConnectSettingActivity;
import com.shqcjd.yunweiyanoperator.ui.adapter.FragPagerAdapter;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.ui.fragment.MineFragment;
import com.shqcjd.yunweiyanoperator.ui.fragment.RemoteGuideFragment;
import com.shqcjd.yunweiyanoperator.ui.fragment.SquareFragment;
import com.shqcjd.yunweiyanoperator.util.AppManager;
import com.shqcjd.yunweiyanoperator.util.IconFontTextView;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.UIUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;
import io.agora.rtc.RtcEngine;

public class MainActivity extends BaseActivity {
    public boolean isKillProcess = true;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.iv_home)
    ImageView ivHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.ll_home)
    LinearLayout llHome;
    @BindView(R.id.iv_square)
    ImageView ivSquare;
    @BindView(R.id.tv_square)
    TextView tvSquare;
    @BindView(R.id.ll_square)
    LinearLayout llSquare;
    @BindView(R.id.iv_mine)
    ImageView ivMine;
    @BindView(R.id.tv_mine)
    TextView tvMine;
    @BindView(R.id.ll_mine)
    LinearLayout llMine;
    private Context mContext;

    private List<Fragment> mFragments = new ArrayList<>();
    private AgoraAPIOnlySignal agoraAPIOnlySignal;

    private final int TIME = 5 * 1000;
    Handler handler=new Handler();
    Runnable runnable=new Runnable() {
        @Override
        public void run() {

            loginAgora();

            handler.postDelayed(this, TIME);
        }
    };

    private void loginAgora() {
        int status = agoraAPIOnlySignal.getStatus();//0: 用户未登录。 1: 用户正在登录。 2: 用户已登录 3: 用户正在重建连接
        Logger.i("登录状态:"+status);
        if (status == 0) {
            initAgora();
        }
    }


    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }


    @Override
    public void init() {
        super.init();
        mContext = this;
        Log.e("token", PrefUtils.getString(mContext, PrefUtils.TOKEN, ""));
        Log.e("uid", PrefUtils.getInt(mContext, PrefUtils.USER_ID, 0)+"--");
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);//订阅
        setTabColor(ivHome,tvHome);
        initFragment();

        initPgy();
        initAgora();


    }

    private void initPgy() {
        //蒲公英
        PgyCrashManager.register(); //推荐使用新版
        /** 蒲公英可选配置集成方式 **/
        new PgyUpdateManager.Builder()
                .setForced(false)                //设置是否强制提示更新
                // v3.0.4+ 以上同时可以在官网设置强制更新最高低版本；网站设置和代码设置一种情况成立则提示强制更新
                .setUserCanRetry(false)         //失败后是否提示重新下载
                .setDeleteHistroyApk(true)     // 检查更新前是否删除本地历史 Apk， 默认为true
                .register();
    }

    private void initAgora() {
        int userId = PrefUtils.getInt(this, PrefUtils.USER_ID, -1);
        int userGuideId = PrefUtils.getInt(this, PrefUtils.USER_GUIDE_ID, -1);
        agoraAPIOnlySignal = MyApp.the().getmAgoraAPI();
        //登出
        agoraAPIOnlySignal.logout();
        Logger.i("Agora 登录用户:" + userGuideId);
        //登录声网信令系统
        agoraAPIOnlySignal.login2(getString(R.string.agora_app_id), userGuideId + "", "_no_need_token", 0, "", 5, 3);
    }

    @Override
    protected void onResume() {
        super.onResume();
        addCallback();
        checkLoginState();
    }

    private void addCallback() {
        agoraAPIOnlySignal.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLoginSuccess(int i, int i1) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.i("Agora 信令登录成功:" + i + "  " + i1);
                    }
                });
            }

            @Override
            public void onLogout(int i) {//103	该账户已在别处登录
                Logger.i("Agora 信令登出"+i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == 103) {
                            EventBus.getDefault().post(new ReloginEvent());
                        }
                    }
                });

            }

            @Override
            public void onLoginFailed(final int i) {
                Logger.e("Agora 信令onLoginFailed");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGIN_E_NET) {
                        }
                    }
                });
            }

            @Override
            public void onError(String s, int i, String s1) {
                Logger.e("Agora 信令onError s:" + s + " i:" + i + " s1:" + s1);
                if (i == 208) {//用户已登录，再次发起登录会触发该错误 可以忽视该错误

                }
            }

            //            呼叫取消时的回调
            @Override
            public void onInviteEndByPeer(String channelID, String account, int uid, String extra) {
                super.onInviteEndByPeer(channelID, account, uid, extra);
                Logger.i("AgoraService：呼叫取消 房间:" + channelID);
//                if (AnswerActivity.getInstance() != null) {
//                    AppManager.getAppManager().finishActivity(AnswerActivity.class);
//                }
            }

            //收到对方呼叫时调用
            @Override
            public void onInviteReceived(String channelID, String account, int uid, String extra) {
                super.onInviteReceived(channelID, account, uid, extra);
                Logger.i("AgoraService：收到呼叫 房间:" + channelID + " 账号:" + account + " 备注:" + extra);
                Intent intent = new Intent(MyApp.getmContext(), AnswerActivity.class);
                intent.putExtra("channelID", channelID);
                intent.putExtra("callerId", account);//主叫方id
                intent.putExtra("info", extra);
                startActivity(intent);

            }

        });
    }

    /**
     * 检测登录状态
     */
    private void checkLoginState() {
        if (handler != null&&runnable!=null) {
            handler.removeCallbacks(runnable);
        }
        handler.postDelayed(runnable, TIME);
    }

    private void initFragment() {
        mFragments.add(RemoteGuideFragment.newInstance());
        mFragments.add(SquareFragment.newInstance());
        mFragments.add(MineFragment.newInstance());

        viewpager.setAdapter(new FragPagerAdapter(getSupportFragmentManager(), mFragments));
        viewpager.setCurrentItem(0, false);
        viewpager.setOffscreenPageLimit(2);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        setTabColor(ivHome, tvHome);
                        break;
                    case 1:
                        setTabColor(ivSquare,tvSquare);
                        break;
                    case 2:
                        setTabColor(ivMine,tvMine);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    @OnClick({R.id.ll_home, R.id.ll_square, R.id.ll_mine})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_home://远程指导
                RemoteGuideFragment rf = (RemoteGuideFragment) mFragments.get(0);
                rf.getMessageNumHttp();
                viewpager.setCurrentItem(0);
                setTabColor(ivHome,tvHome);
                break;
            case R.id.ll_square://广场
                viewpager.setCurrentItem(1);
                setTabColor(ivSquare,tvSquare);
                break;
            case R.id.ll_mine://个人中心
                viewpager.setCurrentItem(2);
                setTabColor(ivMine,tvMine);
                break;
        }
    }
    private void cleanSelect(){
        ivHome.setBackgroundResource(R.mipmap.ic_home_checked_no);
        tvHome.setTextColor(UIUtils.getColor(R.color.main_tab_checked_no));
        ivSquare.setBackgroundResource(R.mipmap.ic_square_checked_no);
        tvSquare.setTextColor(UIUtils.getColor(R.color.main_tab_checked_no));
        ivMine.setBackgroundResource(R.mipmap.ic_mine_checke_no);
        tvMine.setTextColor(UIUtils.getColor(R.color.main_tab_checked_no));
    }

    private void setTabColor(ImageView icon, TextView textView) {
        cleanSelect();
        switch (icon.getId()) {
            case R.id.iv_home:
                icon.setBackgroundResource(R.mipmap.ic_home_checked);
                break;
            case R.id.iv_square:
                icon.setBackgroundResource(R.mipmap.ic_square_checked);
                break;
            case R.id.iv_mine:
                icon.setBackgroundResource(R.mipmap.ic_mine_checke);
                break;
        }
        textView.setTextColor(UIUtils.getColor(R.color.main_tab_checked));
    }

    public long preTime;
    public final long TWO_SECOND = 2 * 1000;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - preTime > TWO_SECOND) {
                ToastUtils.show(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT);
                // 更新时间
                preTime = System.currentTimeMillis();

            } else {
                MainActivity.this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出登录
     */
    private void signOut() {
        agoraAPIOnlySignal.logout();//退出信令
        isKillProcess = false;
        PrefUtils.setBoolean(this, PrefUtils.FIRST_LOGIN, false);
        PrefUtils.setInt(this, PrefUtils.USER_ID, -1);
        PrefUtils.setString(this, PrefUtils.USER_CODE, "");
        PrefUtils.setString(this, PrefUtils.USER_NAME, "");
        PrefUtils.setString(this, PrefUtils.PHONE_NUMBER, "");
        PrefUtils.setString(this, PrefUtils.USER_ICON, "");
        PrefUtils.setString(this, AppConstant.TOKEN_KEY, "");
        PrefUtils.setInt(this, PrefUtils.USER_TYPE, -1);
        PrefUtils.setString(this, PrefUtils.USER_ACCOUNT, "");
        PrefUtils.setString(this, PrefUtils.USER_PWD, "");
        PrefUtils.setString(this, PrefUtils.TOKEN, "");
        PrefUtils.setInt(this, PrefUtils.USER_STATE, -1);
        PrefUtils.setString(this, PrefUtils.BUSINESSId, "");
        PrefUtils.setString(this, PrefUtils.APPCODE, "");
        PrefUtils.setInt(mContext, PrefUtils.ORGANIZATION_TYPE, -1);
        PrefUtils.setString(mContext, PrefUtils.BUSINESSNAME, "");
        new TagAliasUtils().TagAliasUtils("");
        AppManager.getAppManager().finishAllActivity();
        Intent it = new Intent(this, LoginActivity.class);
        startActivity(it);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//解除订阅

        if (handler != null&&runnable!=null) {
            handler.removeCallbacks(runnable);
        }


//        if (isKillProcess) {
//            RtcEngine.destroy();//销毁rtc实例
//            android.os.Process.killProcess(android.os.Process.myPid());//杀死进程
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onFinishActivityEvent(FinishActivityEvent event) {
        if (event.isToken) {
            signOut();
        } else {
            showOutDialog();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReloginEvent(ReloginEvent reloginEvent){//帐号在别处登录，重新登录
        ToastUtils.showLong(mContext,"该账户已在别处登录");
        signOut();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTokenOvertimeEvent(TokenOvertimeEvent event){//token超时，重新登录
        ToastUtils.showLong(mContext,"登录信息过期,请重新登录");
        signOut();
    }



    private void showOutDialog() {
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.custome_out_view, false)
                .show();

        View customeView = dialog.getCustomView();

        TextView cancel = customeView.findViewById(R.id.tv_cancel);
        TextView confirm = customeView.findViewById(R.id.tv_confirm);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                signOut();
            }
        });
    }




}
